package com.kob.backend.consumer;

import com.alibaba.fastjson.JSONObject;
import com.kob.backend.consumer.utils.Game;
import com.kob.backend.consumer.utils.JwtAuthentication;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务类
 *
 * @Author: CZY
 * @date: 2024/9/2 14:15
 */
@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾
public class WebSocketServer {

    // 保存所有当前在线用户的 WebSocket 连接。键是用户的 userId，值是当前用户的 WebSocketServer 实例。
    final public static ConcurrentHashMap<Integer, WebSocketServer> users = new ConcurrentHashMap<>();
    private User user;  // 表示当前 WebSocket 连接对应的用户。
    private Session session = null;

    public static UserMapper userMapper;
    public static RecordMapper recordMapper;
    private static BotMapper botMapper;
    public static RestTemplate restTemplate;    // 发送 HTTP 请求，与其他微服务进行通信
    public Game game = null;    // 表示当前用户正在进行的游戏实例
    private final static String addPlayerUrl = "http://127.0.0.1:3001/player/add/";
    private final static String removePlayerUrl = "http://127.0.0.1:3001/player/remove/";

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void setBotMapper(BotMapper botMapper) {
        WebSocketServer.botMapper = botMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        WebSocketServer.restTemplate = restTemplate;
    }

    // WebSocket 连接打开时调用
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        this.session = session;
        Integer userId = JwtAuthentication.getUserId(token);
        this.user = userMapper.selectById(userId);

        if (this.user != null) {
            users.put(userId, this);
            users.put(5, this);     // 添加机器人用户
        } else {
            this.session.close();
        }
//        System.out.println(users);
    }

    // WebSocket 连接关闭时调用
    @OnClose
    public void onClose() {
        if (this.user != null) {
            users.remove(this.user.getId());
            users.remove(5);

            // 问题描述: 开始匹配后，刷新页面，断开连接，再次匹配，会发生自己和自己匹配
            // 解决方案: 断开链接时，删除已经存在在匹配池里的player信息，避免自己和自己匹配
            MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
            data.add("user_id", this.user.getId().toString());
            restTemplate.postForObject(removePlayerUrl, data, String.class);
        }
    }

    // 开始游戏
    public static void startGame(Integer aId, Integer aBotId, Integer bId, Integer bBotId, String difficulty) {
        User a = userMapper.selectById(aId), b = userMapper.selectById(bId);
        Bot botA = botMapper.selectById(aBotId), botB = botMapper.selectById(bBotId);

        Game game = new Game(
                13,
                14,
                20,
                a.getId(),
                botA,
                b.getId(),
                botB,
                difficulty
        );
        game.createMap();
        if (users.get(a.getId()) != null) {
            users.get(a.getId()).game = game;
        }
        if (users.get(b.getId()) != null) {
            users.get(b.getId()).game = game;
        }
        game.start();

        JSONObject respGame = new JSONObject();
        respGame.put("a_id", game.getPlayerA().getId());
        respGame.put("a_sx", game.getPlayerA().getSx());
        respGame.put("a_sy", game.getPlayerA().getSy());
        respGame.put("b_id", game.getPlayerB().getId());
        respGame.put("b_sx", game.getPlayerB().getSx());
        respGame.put("b_sy", game.getPlayerB().getSy());
        respGame.put("map", game.getG());

        JSONObject respA = new JSONObject();
        if ("none".equals(difficulty)) {
            respA.put("event", "start-matching");
        } else {
            respA.put("event", "start-botmatching");
        }
        respA.put("opponent_username", b.getUsername());
        respA.put("opponent_photo", b.getPhoto());
        respA.put("game", respGame);
        if (users.get(a.getId()) != null) {
            users.get(a.getId()).sendMessage(respA.toJSONString());
        }

        JSONObject respB = new JSONObject();
        if ("none".equals(difficulty)) {
            respB.put("event", "start-matching");
        } else {
            respB.put("event", "start-botmatching");
        }
        respB.put("opponent_username", a.getUsername());
        respB.put("opponent_photo", a.getPhoto());
        respB.put("game", respGame);
        if (users.get(b.getId()) != null && b.getId() != 5) {
            users.get(b.getId()).sendMessage(respB.toJSONString());
        }
    }

    // 开始匹配
    private void startMatching(Integer botId) {
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        data.add("rating", this.user.getRating().toString());
        data.add("bot_id", botId.toString());
        restTemplate.postForObject(addPlayerUrl, data, String.class);
    }

    private void startBotMatching(Integer botId, String difficulty) {
        int botCodeId = -1;
        switch (difficulty) {
            case "easy":
                botCodeId = 2;
                break;
            case "common":
                botCodeId = 3;
                break;
            case "hard":
                botCodeId = 4;
                break;
        }

        Bot botA = botMapper.selectById(botId), botB = botMapper.selectById(botCodeId);
        Game game = new Game(
                13,
                14,
                28,
                this.user.getId(),
                botA,
                this.user.getId(),
                botB,
                difficulty
        );
        game.createMap();
        users.get(this.user.getId()).game = game;
        game.start();
        JSONObject respGame = new JSONObject();
        respGame.put("a_id", game.getPlayerA().getId());
        respGame.put("a_sx", game.getPlayerA().getSx());
        respGame.put("a_sy", game.getPlayerA().getSy());
        respGame.put("b_id", game.getPlayerB().getId());
        respGame.put("b_sx", game.getPlayerB().getSx());
        respGame.put("b_sy", game.getPlayerB().getSy());
        respGame.put("map", game.getG());

        JSONObject respA = new JSONObject();
        if ("none".equals(difficulty)) {
            respA.put("event", "start-matching");
        } else {
            respA.put("event", "start-botmatching");
        }
        respA.put("game", respGame);
        if (users.get(this.user.getId()) != null) {
            users.get(this.user.getId()).sendMessage(respA.toJSONString());
        }
    }

    // 停止匹配
    private void stopMatching() {
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        restTemplate.postForObject(removePlayerUrl, data, String.class);
    }

    private void move(int direction) {
//        System.out.println("move " + direction);
        if (game.getPlayerA().getId().equals(user.getId())) {   // 若为玩家A
            if (game.getPlayerA().getBotId().equals(-1)) {   // 亲自出马，避免bot执行时发生冲突
                game.setNextStepA(direction);
            }
        } else if (game.getPlayerB().getId().equals(user.getId())) {
            if (game.getPlayerB().getBotId().equals(-1)) {
                game.setNextStepB(direction);
            }
        }
    }

    // 当服务器接收到客户端发送的消息时触发。
    @OnMessage
    public void onMessage(String message, Session session) {  // 当做路由
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if ("start-matching".equals(event)) {
            startMatching(data.getInteger("bot_id"));
        } else if ("start-botmatching".equals(event)) {
            startBotMatching(data.getInteger("bot_id"), data.getString("difficulty"));
        } else if ("stop-matching".equals(event)) {
            stopMatching();
        } else if ("move".equals(event)) {
            move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    // 将服务器端的消息发送给当前连接的客户端
    public void sendMessage(String message) {
        synchronized (this.session) {   // 异步通信加锁
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}